﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using TBM.Tools;
using TBM.Filters;
using TBM.Attributes;
using System.Web;

namespace TBM.Controllers
{
    public partial class UserController : MasterController
    {
        [Description("用户组管理")]
        [TBMAuthorize("用户管理", "用户组管理")]
        public ActionResult GroupList(int? p)
        {
            PageNavigationBar pnb = new PageNavigationBar("p", Core.Config.PageSize, Core.Config.DisplayPageCount);

            cmd.CommandText = "p_GetGroups";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@PageSize", SqlDbType.Int);
            cmd.Parameters.Add("@CurrPage", SqlDbType.Int);
            cmd.Parameters.Add("@RecordCount", SqlDbType.Int);
            cmd.Parameters["@PageSize"].Value = pnb.PageSize;
            cmd.Parameters["@CurrPage"].Value = pnb.CurrPage;
            cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;

            List<Models.Group> groups = new List<Models.Group>();

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    groups.Add(new Models.Group
                    {
                        GID = dr["GID"].ToString(),
                        GroupName = dr["GroupName"].ToString(),
                        Descr = dr["Descr"].ToString(),
                        MemberCount = (int)dr["MemberCount"]
                    });
                }
            }

            pnb.Count = (int)cmd.Parameters["@RecordCount"].Value;

            ViewBag.PageNav = pnb.Create();

            if (IsAjaxRequest)
            {
                return PartialView("GroupTable", groups);
            }

            cmd.CommandText = "select UID, FirstName, LastName, PicUrl, CNName from dbo.Users";
            cmd.CommandType = CommandType.Text;

            List<Models.User> users = new List<Models.User>();
            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    users.Add(new Models.User
                    {
                        UID = dr["UID"].ToString(),
                        FirstName = dr["FirstName"].ToString(),
                        LastName = dr["LastName"].ToString(),
                        PicUrl = dr["PicUrl"].ToString(),
                        CNName = (bool)dr["CNName"]
                    });
                }
            }

            ViewBag.Users = users;

            return View(groups);
        }

        [ChildActionOnly]
        public ActionResult GroupTable()
        {
            return PartialView();
        }

        /// <summary>
        /// 删除分组
        /// </summary>
        /// <param name="confirmpwd">确认当前密码</param>
        /// <param name="gids">GID列表</param>
        /// <returns></returns>
        [ParentAction("GroupList")]
        [Description("删除分组")]
        [TBMAuthorize("用户管理", "删除分组")]
        public JsonResult DeleteGroup(string confirmpwd, string[] gids)
        {
            JsonResult result = new JsonResult();

            if (!Core.App.CheckPassword(confirmpwd))
            {
                result.Data = new Models.ExecuteResult
                {
                    Result = false,
                    Code = Core.Lang.REQUEST_CHECK_PWD_FAILED.Code,
                    Message = Core.Lang.REQUEST_CHECK_PWD_FAILED.Message
                };

                return result;
            }

            cmd.CommandText = "delete from dbo.Groups where GID in (select item from fn_Split(@GIDS, ',') where item != '_admin')";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@GIDS", SqlDbType.VarChar, 500);
            cmd.Parameters["@GIDS"].Value = String.Join(",", gids);

            Core.LangItem li = cmd.ExecuteNonQuery() > 0 ? Core.Lang.CMD_SUCCESS : Core.Lang.DELETE_GROUP_FAILED;

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message
            };

            return result;
        }

        /// <summary>
        /// 添加分组
        /// </summary>
        /// <param name="gid">新的GID</param>
        /// <param name="groupname">组名称</param>
        /// <param name="descr">组描述</param>
        /// <returns></returns>
        [ParentAction("GroupList")]
        [Description("添加分组")]
        [TBMAuthorize("用户管理", "添加分组")]
        public JsonResult AddGroup(string gid, string groupname, string descr)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = @"if not exists(select * from dbo.Groups where GID = @GID)
                                insert into dbo.Groups(GID, GroupName, Descr) values(@GID, @GroupName, @Descr)";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@GID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@GroupName", SqlDbType.NVarChar, 10);
            cmd.Parameters.Add("@Descr", SqlDbType.NVarChar, 30);
            cmd.Parameters["@GID"].Value = gid.ToLower();
            cmd.Parameters["@GroupName"].Value = groupname;
            cmd.Parameters["@Descr"].Value = descr;

            Core.LangItem li = cmd.ExecuteNonQuery() > 0 ? Core.Lang.CMD_SUCCESS : Core.Lang.EXISTS_GID;

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message
            };

            return result;
        }


        /// <summary>
        /// 添加用户到组
        /// </summary>
        /// <param name="gids">组ID列表</param>
        /// <param name="uids">被添加用户ID列表</param>
        /// <returns></returns>
        [ParentAction("GroupList")]
        [Description("添加用户到组")]
        [TBMAuthorize("用户管理", "添加用户到组")]
        public JsonResult JoinToGroup(string[] gids, string[] uids)
        {
            return _UserToGroup(gids, uids);
        }


        /// <summary>
        /// 分组详情页
        /// </summary>
        /// <param name="gid">GID</param>
        /// <returns></returns>
        [ParentAction("GroupList")]
        [Description("分组详情")]
        [TBMAuthorize("用户管理", "分组详情")]
        public ActionResult GroupDetail(string gid)
        {
            cmd.CommandText = @"select U.UID, case when CNName = 1 then FirstName + LastName else LastName + ' ' + FirstName end as FullName, 
                                    cast(case when M.UID is null then 0 else 1 end as bit) as IsChecked 
                                    from dbo.Users as U left join dbo.MemberShip as M on U.UID = M.UID and M.GID = @GID";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@GID", SqlDbType.VarChar, 15);
            cmd.Parameters["@GID"].Value = gid;

            List<Models.UserListItem> users = new List<Models.UserListItem>();

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    users.Add(new Models.UserListItem
                    {
                        UID = dr["UID"].ToString(),
                        FullName = dr["FullName"].ToString(),
                        Checked = (bool)dr["IsChecked"]
                    });
                }
            }

            Models.Group group = new Models.Group();
            cmd.CommandText = @"select GID, GroupName, Descr from dbo.Groups where GID = @GID";

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                if (dr.Read())
                {
                    group.GID = dr["GID"].ToString();
                    group.GroupName = dr["GroupName"].ToString();
                    group.Descr = dr["Descr"].ToString();
                }
            }

            List<Models.Module> modules = new List<Models.Module>();
            Dictionary<Models.Module, List<Models.Module>> moduleList = new Dictionary<Models.Module, List<Models.Module>>();
            cmd.CommandText = "p_ModulesInGroup";
            cmd.CommandType = CommandType.StoredProcedure;

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    modules.Add(new Models.Module
                    {
                        ID = (int)dr["ID"],
                        PID = (int)dr["PID"],
                        ControllerName = dr["ControllerName"].ToString(),
                        ControllerDescr = dr["ControllerDescr"].ToString(),
                        ActionDescr = dr["ActionDescr"].ToString(),
                        ActionName = dr["ActionName"].ToString(),
                        IsActived = (bool)dr["IsActived"],
                        IsChecked = (bool)dr["IsChecked"]
                    });
                }
            }

            foreach (Models.Module module in modules.Where(item => item.PID == 0))
            {
                moduleList.Add(module, modules.Where(item => item.PID == module.ID).ToList());
            }

            ViewBag.Users = users;
            ViewBag.Group = group;
            ViewBag.ModuleList = moduleList;
            ViewBag.MainMenu = GetObjectMenu(gid, 1);

            return View();
        }


        /// <summary>
        /// 更新分组信息
        /// </summary>
        /// <param name="gid">GID</param>
        /// <param name="groupname">组名</param>
        /// <param name="descr">组描述</param>
        /// <returns></returns>
        [ParentAction("GroupList")]
        [Description("更新组信息")]
        [TBMAuthorize("用户管理", "更新组信息")]
        public JsonResult UpdateGrouop(string gid, string groupname, string descr)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = "update dbo.Groups set GroupName = @GroupName, Descr = @Descr where GID = @GID";
            cmd.Parameters.Add("@GID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@GroupName", SqlDbType.NVarChar, 10);
            cmd.Parameters.Add("@Descr", SqlDbType.NVarChar, 30);
            cmd.Parameters["@GID"].Value = gid;
            cmd.Parameters["@GroupName"].Value = groupname;
            cmd.Parameters["@Descr"].Value = descr;

            Core.LangItem li = cmd.ExecuteNonQuery() > 0 ? Core.Lang.CMD_SUCCESS : Core.Lang.CMD_FAILED;

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message,
                Data = new { 
                    GID = gid,
                    GroupName = groupname,
                    Descr = descr
                }
            };

            return result;
        }


        /// <summary>
        /// 变更组成员
        /// </summary>
        /// <param name="gid">GID</param>
        /// <param name="uids">成员ID</param>
        /// <returns></returns>
        [ParentAction("GroupList")]
        [Description("变更组成员")]
        [TBMAuthorize("用户管理", "变更组成员")]
        public JsonResult ChangeMember(string gid)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = @"delete from dbo.MemberShip where GID = @GID; 
                                insert into dbo.MemberShip (GID, UID) select @GID, Item from fn_Split(@UIDs, ',');
                                select count(*) from dbo.MemberShip where GID = @GID;";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@GID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@UIDs", SqlDbType.VarChar, 500);
            cmd.Parameters["@GID"].Value = gid;
            cmd.Parameters["@UIDs"].Value = Core.CommandParamType.NullOrString(Request["uids"]);

            result.Data = new Models.ExecuteResult
            {
                Result = true,
                Code = Core.Lang.CMD_SUCCESS.Code,
                Message = Core.Lang.CMD_SUCCESS.Message,
                Data = new
                {
                    GID = gid,
                    Count = (int)cmd.ExecuteScalar()
                }
            };

            return result;
        }


        /// <summary>
        /// 更新用户权限
        /// </summary>
        /// <param name="gid">用户UID</param>
        /// <returns></returns>
        [ParentAction("GroupList")]
        [Description("更新组模块权限")]
        [TBMAuthorize("用户管理", "更新组模块权限")]
        public JsonResult UpdateGroupPermission(string gid)
        {
            return _UpdatePermission(gid);
        }


        /// <summary>
        /// 更新用户权限
        /// </summary>
        /// <param name="gid">用户UID</param>
        /// <returns></returns>
        [ParentAction("GroupList")]
        [Description("更新组页面权限")]
        [TBMAuthorize("用户管理", "更新组页面权限")]
        public JsonResult UpdateGroupMenuPermission(string gid)
        {
            return _UpdateMenuPermission(gid);
        }
    }
}
